<script setup>
import {onMounted, ref} from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";
import {linkAdd, linkDelete, linkList, linkUpdate} from "../api/link.js";
import {useStore} from "vuex";

const store = useStore();

// 查询条件
const queryInfo = ref({
    pageNo: 1,
    pageSize: 10,
    category_id: "",
    title: ""
});

// 发布时间
const createRange = ref([]);

// 时间快捷选项 输出格式为  date 00:00:00 - date 23:59:59
const shortcuts = [
    {
        text: '今天',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setHours(0, 0, 0, 0);
            end.setHours(23, 59, 59, 999);
            return [start, end];
        },
    },
    {
        text: '昨天',
        value: () => {
            const today = new Date();
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            const start = new Date(yesterday);
            start.setHours(0, 0, 0, 0);
            const end = new Date(yesterday);
            end.setHours(23, 59, 59, 999);
            return [start, end];
        },
    },
    {
        text: '最近一周',
        value: () => {
            const today = new Date();
            const oneWeekAgo = new Date(today);
            oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
            const start = new Date(oneWeekAgo);
            start.setHours(0, 0, 0, 0);
            const end = new Date(today);
            end.setHours(23, 59, 59, 999);
            return [start, end];
        },
    },
    {
        text: '最近一月',
        value: () => {
            const today = new Date();
            const oneMonthAgo = new Date(today);
            oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
            const start = new Date(oneMonthAgo);
            start.setHours(0, 0, 0, 0);
            const end = new Date(today);
            end.setHours(23, 59, 59, 999);
            return [start, end];
        },
    },
    {
        text: '最近三月',
        value: () => {
            const today = new Date();
            const threeMonthsAgo = new Date(today);
            threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
            const start = new Date(threeMonthsAgo);
            start.setHours(0, 0, 0, 0);
            const end = new Date(today);
            end.setHours(23, 59, 59, 999);
            return [start, end];
        },
    },
];

// 数据列表
const dataList = ref([]);

const total = ref(0);

// 添加表单
const addForm = ref({
    state: 1
});

// 修改表单
const editForm = ref({});

// 添加弹窗
const showAddDialog = ref(false);

// 编辑弹窗
const showEditDialog = ref(false);

// 获取数据
const getDataList = () => {
    if (createRange.value.length > 0) {
        queryInfo.value.create_time_start = createRange.value[0];
        queryInfo.value.create_time_end = createRange.value[1];
    }

    linkList(queryInfo.value).then((res) => {
        if (res.code === 200) {
            dataList.value = res.data.list;
            total.value = res.data.total || 0;
        } else {
            ElMessage.error(res.msg);
        }
    }).catch((err) => {
        console.log(err);
    });
}

// 重置数据
const resetDataList = () => {
    createRange.value = [];
    queryInfo.value = {
        pageNo: 1,
        pageSize: 10
    };
    getDataList();
}

// 删除数据
const deleteById = async (id) => {
    const confirmResult = await ElMessageBox.confirm(
        "此操作将永久删除该记录, 是否继续?",
        "提示",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }
    );

    if (confirmResult === "confirm") {
        linkDelete(id).then((res) => {
            if (res.code === 200) {
                getDataList();
                ElMessage.success("删除成功");
            } else {
                ElMessage.error("删除失败");
            }
        }).catch((err) => {
            console.log(err);
            ElMessage.error("删除异常");
        });
    }
}

// 分页大小
const handleSizeChange = (newSize) => {
    queryInfo.value.pageSize = newSize;
    getDataList();
}

// 切换页码
const handleCurrentChange = (newPage) => {
    queryInfo.value.pageNo = newPage;
    getDataList();
}

// 监听
const showEditDiag = async (row) => {
    editForm.value = row
    showEditDialog.value = true;
}

const addData = async () => {
    try {
        const res = await linkAdd(addForm.value);
        if (res.code === 200) {
            ElMessage.success("添加成功");
            showAddDialog.value = false;
            addForm.value = {};
            getDataList();
        } else {
            ElMessage.error(res.msg);
        }
    } catch (err) {
        console.error(err);
        ElMessage.error("添加异常");
    }
}

// 编辑链接
const editData = async () => {
    try {
        const res = await linkUpdate(editForm.value);
        if (res.code === 200) {
            ElMessage.success("更新成功");
            showEditDialog.value = false;
            getDataList();
        } else {
            ElMessage.error(res.msg);
        }
    } catch (err) {
        console.error(err);
        ElMessage.error("更新异常");
    }
}

// 状态
const stateOptions = [
    {
        value: 1,
        label: "启用"
    },
    {
        value: 0,
        label: "禁用"
    }
]

// 加载数据
onMounted(() => {
    getDataList();
})
</script>

<template>
    <el-container class="el-container-fix">
        <el-header height="80">
            <el-row :gutter="20">

                <el-col :span="3">
                    <el-input
                        placeholder="数字ID"
                        v-model="queryInfo.no_id"
                        clearable
                        @clear="getDataList"
                        @keydown.enter="getDataList"
                    >
                        <template #prepend>数字ID</template>
                    </el-input>
                </el-col>

                <el-col :span="4">
                    <el-input
                        placeholder="别名"
                        v-model="queryInfo.cust_name"
                        clearable
                        @clear="getDataList"
                        @keydown.enter="getDataList"
                    >
                        <template #prepend>别名</template>
                    </el-input>
                </el-col>

                <el-col :span="3">
                    <el-input
                        placeholder="短链接ID"
                        v-model="queryInfo.hash_id"
                        clearable
                        @clear="getDataList"
                        @keydown.enter="getDataList"
                    >
                        <template #prepend>短链接ID</template>
                    </el-input>
                </el-col>

                <el-col :span="4">
                    <el-input
                        placeholder="原始链接"
                        v-model="queryInfo.long_url"
                        clearable
                        @clear="getDataList"
                        @keydown.enter="getDataList"
                    >
                        <template #prepend>原始链接</template>
                    </el-input>
                </el-col>

                <el-col :span="4">
                    <el-select
                        placeholder="状态"
                        v-model="queryInfo.state"
                        clearable
                        @clear="getDataList"
                        @keydown.enter="getDataList"
                    >
                        <el-option
                            v-for="item in stateOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-col>
            </el-row>

            <el-row :gutter="20" class="mt-2">
                <el-col :span="6">
                    <el-date-picker
                        v-model="createRange"
                        :shortcuts="shortcuts"
                        type="datetimerange"
                        start-placeholder="发布开始时间"
                        end-placeholder="发布结束时间"
                        format="YYYY/MM/DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                    ></el-date-picker>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="getDataList">
                        查询
                    </el-button>
                    <el-button type="info" @click="resetDataList">
                        重置
                    </el-button>
                    <el-button type="success" @click="showAddDialog = true">
                        添加
                    </el-button>
                </el-col>
            </el-row>
        </el-header>

        <el-main>
            <el-table
                :data="dataList"
                height="600"
                ref="filterTable"
                :border="true"
                stripe
            >
                <el-table-column prop="id" label="id" width="80"></el-table-column>
                <el-table-column prop="no_id" label="数字ID">
                    <template #default="scope">
                        <el-link :href="store.state.app.host +'/' + scope.row.no_id" target="_blank">{{ scope.row.no_id }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="cust_name" label="别名">
                    <template #default="scope">
                        <el-link :href="store.state.app.host +'/' + scope.row.cust_name" target="_blank">{{ scope.row.cust_name }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="hash_id" label="短链接ID">
                    <template #default="scope">
                        <el-link :href="store.state.app.host +'/' + scope.row.hash_id" target="_blank">{{ scope.row.hash_id }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="long_url" label="原始链接"></el-table-column>
                <el-table-column prop="click" label="点击数"></el-table-column>
                <el-table-column prop="state" label="状态">
                    <template #default="scope">
                        <el-tag v-if="scope.row.state === 0" type="danger">禁用</el-tag>
                        <el-tag v-if="scope.row.state === 1" type="success">启用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="last_access_at" label="上次访问时间"></el-table-column>
                <el-table-column prop="create_at" label="创建时间"></el-table-column>
                <el-table-column prop="update_at" label="更新时间"></el-table-column>
                <el-table-column label="操作" width="260">
                    <template #default="scope">
                        <el-button
                            size="small"
                            type="primary"
                            icon="Edit"
                            @click="showEditDiag(scope.row)"
                        >编辑
                        </el-button>
                        <el-button
                            size="small"
                            type="danger"
                            icon="Delete"
                            @click="deleteById(scope.row.id)"
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>

        <el-row>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pageNo"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="queryInfo.pageSize"
                :total="total"
                layout="total,prev, pager, next,jumper,sizes"
            >
            </el-pagination>
        </el-row>
    </el-container>

    <!--添加链接的对话框-->
    <el-dialog
        title="添加链接"
        v-model="showAddDialog"
        width="800px"
        align-center
        @close="showAddDialog = false"
    >
        <el-form :model="addForm" label-width="100px" ref="addFormRef">
            <el-form-item label="数字ID" prop="no_id">
                <el-input-number v-model="addForm.no_id" placeholder="请输入数字ID"></el-input-number>
            </el-form-item>

            <!--            <el-form-item label="短链接ID" prop="hash_id">-->
            <!--                <el-input v-model="addForm.hash_id" placeholder="请输入短链接ID"></el-input>-->
            <!--            </el-form-item>-->

            <el-form-item label="别名" prop="cust_name">
                <el-input v-model="addForm.cust_name" placeholder="请输入别名"></el-input>
            </el-form-item>

            <el-form-item label="原始链接" prop="long_url">
                <el-input v-model="addForm.long_url" placeholder="请输入原始链接"></el-input>
            </el-form-item>

            <el-form-item label="状态" prop="state">
                <el-select v-model="addForm.state" placeholder="请选择状态">
                    <el-option label="禁用" :value="0"></el-option>
                    <el-option label="启用" :value="1"></el-option>
                </el-select>
            </el-form-item>

        </el-form>
        <template #footer class="dialog-footer">
            <el-button type="primary" @click="addData">确 定</el-button>
            <el-button @click="showAddDialog = false">取 消</el-button>
        </template>
    </el-dialog>

    <!--修改游戏的对话框-->
    <el-dialog title="修改链接" v-model="showEditDialog" width="50%" @close="showEditDialog=false">
        <el-form :model="editForm" label-width="100px" ref="editFormRef">
            <el-form-item label="数字ID" prop="no_id">
                <el-input-number v-model="editForm.no_id" placeholder="请输入数字ID"></el-input-number>
            </el-form-item>

            <el-form-item label="别名" prop="cust_name">
                <el-input v-model="editForm.cust_name" placeholder="请输入别名"></el-input>
            </el-form-item>

            <el-form-item label="短链接ID" prop="hash_id">
                <el-input v-model="editForm.hash_id" placeholder="请输入短链接ID"></el-input>
            </el-form-item>

            <el-form-item label="原始链接" prop="long_url">
                <el-input v-model="editForm.long_url" placeholder="请输入原始链接"></el-input>
            </el-form-item>

            <el-form-item label="状态" prop="state">
                <el-select v-model="editForm.state" placeholder="请选择状态">
                    <el-option label="禁用" :value="0"></el-option>
                    <el-option label="启用" :value="1"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer class="dialog-footer">
            <el-button type="primary" @click="editData">确 定</el-button>
            <el-button @click="showEditDialog = false">取 消</el-button>
        </template>
    </el-dialog>
</template>

<style scoped>
.el-container-fix {
    width: 98%;
    margin: auto;
    padding: 20px 0;
}

.mt-2 {
    margin: 20px 0;
}

.dialog-footer {
    width: 100%;
    display: block;
    text-align: center;
}
</style>